#!/usr/bin/env Python
# coding=utf-8

import random
import socket
import handlers.base as baseHandler
from datetime import *
import time

import methods.database.orm.room as room
import methods.database.orm.room_player as room_player
import json
class RoomHandler(baseHandler.BaseHandler):
    def get(self):
        room_id = self.get_argument("room_id")
        roomData = {"room_id": str(room_id)}
        username = self.get_cookie("xxgame_username")
        result={"room_id": room_id , "username":username}
        flag=checkRoom(roomData)
        if flag>0:
            self.set_cookie("xxgame_roomId", room_id)  # 将当前的房间名存到cookie
            self.render("game/room.html", result=result)
        else:
            self.render("base/error.html",msg="你输入的房间号不存在")

class CreateRoomHandler(baseHandler.BaseHandler):
    def post(self):
        username=self.get_cookie("xxgame_username")
        localIP = socket.gethostbyname(socket.gethostname())  # 得到本地ip
        roomData = {"username": username}
        check_room_id = checkRoom(roomData)
        room_id = random.randint(10000, 100000)
        if check_room_id>0:
            self.write({"status": 1, "msg":"你已经开好房间了，房间号为："+str(check_room_id)})
        else:
            while(True):
                roomData = {"room_id": str(room_id)}
                check_room_id = checkRoom(roomData)
                if check_room_id>0:
                    room_id = random.randint(10000, 100000)
                else:
                    break
            data = {"username": str(username), "room_id": str(room_id), "create_time": time.strftime( '%Y-%m-%d %X', time.localtime() )}
            data_player = {"username": str(username), "room_id": str(room_id), "enter_time":time.strftime( '%Y-%m-%d %X', time.localtime() ), "user_ip": str(localIP)}
            room.createRoom(data)
            room_player.enterRoom(data_player)
            self.write({"status": 0, "msg": room_id})

class JoinRoomHandler(baseHandler.BaseHandler):
    def post(self):
        username=self.get_cookie("xxgame_username")
        #首先校验该用户是否已经加入了房间，优先进入已经加入的房间
        roomData = {"username": username}
        check_room_id = checkRoom(roomData)
        if check_room_id > 0:  # 该房间号存在,或者用户已经加入了某个房间
            self.write({"status": 0, "msg": check_room_id})
            return
        data = json.loads(self.request.body)
        room_id = data["room_id"]
        if room_id=='':#不是该用户主动发起的申请，需要过滤
            self.write({"status": 1, "msg": check_room_id})
            return
        roomData = {"room_id": str(room_id)}
        check_room_id = checkRoom(roomData)
        if check_room_id>0:#该房间号存在
            localIP = socket.gethostbyname(socket.gethostname())  # 得到本地ip
            data_player = {"username": str(username), "room_id": str(room_id), "enter_time": time.strftime( '%Y-%m-%d %X', time.localtime() ),"user_ip": str(localIP)}
            room_player.enterRoom(data_player)
            self.write({"status": 0, "msg": room_id})
        else:
            self.write({"status": 2, "msg": "房间号不存在"})

class QuitRoomHandler(baseHandler.BaseHandler):
    def post(self):
        username=self.get_cookie("xxgame_username")
        room_player.quitRoom(username)
        self.write({"status": 0, "msg": "退出成功"})

def checkRoom(param):
    room_infos = room.getRoomInfo(param)
    playerParam=""
    if room_infos == None:
        room_id=0
        for i in param:
            if i=='username':
                playerParam={"username":param[i]}
        if playerParam:
            room_infos = room_player.getRoomPlayer(playerParam)
            if room_infos:
                room_id=room_infos.room_id
    else:
        if (room_infos.begin_time == None or room_infos.end_time == None):
            room_id=room_infos.room_id
        else:
            nowDate = datetime.today()
            if (nowDate > room_infos.begin_time and nowDate < room_infos.end_time):
                room_id = room_infos.room_id
            else:
                room_id = 0
    return room_id